package com.merugu.school.beans;

import java.awt.event.ActionEvent;
import java.rmi.activation.ActivationInstantiator;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.merugu.school.spring.UserDao;
import com.merugu.school.util.JsfUtil;

/**
 * Represents the springUserBean User: raveendramerugu Date: Dec 5, 2010 Time:
 * 11:29:00 PM
 */

@ManagedBean(name = UserBean.BEAN_NAME)
@SessionScoped
public class UserBean {

	public static final String BEAN_NAME = "userBean";
	public static final Logger LOGGER = Logger.getLogger(UserBean.class
			.getName());

	public UserBean() {
		LOGGER.info("User bean is created....");
	}

	private String userName;
	private String password;
	private String firstName;
	private String lastName;
	private String userRole;
	private boolean admin;

	public UserBean(String lastName, String firstName, String userName) {
		this.lastName = lastName;
		this.firstName = firstName;
		this.userName = userName;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getUserRole() {
		return userRole;
	}

	public void setUserRole(String userRole) {
		this.userRole = userRole;
	}

	/**
	 * Action method for login action
	 * 
	 * @return Page id or page path
	 */
	public String login() {
		UserBean bean = UserDao.getUserDao()
				.login(getUserName(), getPassword());
		if (bean != null) {
			LOGGER.log(Level.INFO,
					"login successful .....  " + bean.getUserName());
			return "/pages/home.jsf";
		} else {
			JsfUtil.addErrorMessage(null, "User id or password incorrect");
		}
		return null;
	}

	/**
	 * Inserts new User into the system
	 */
	public String insert() {
		LOGGER.info("Inserting User  ....");
		UserDao.getUserDao().insertUser(this);
		return null;
	}

	public void update() {
		LOGGER.info("Updating the user object" + getUserName());
		UserDao.getUserDao().updateUser(this);
	}

	/**
	 * Returns the current instance of UserBean
	 * 
	 * @return UserBean
	 */
	public static UserBean getUserBean() {
		UserBean userBean = JsfUtil.findManagedBean(BEAN_NAME, UserBean.class);
		return userBean;
	}

	public boolean isAdmin() {
		admin = "admin".equalsIgnoreCase(getUserRole());
		return admin;
	}

	public void setAdmin(boolean admin) {
		this.admin = admin;
	}
}
